package com.bert.config;

import org.apache.logging.log4j.ThreadContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Configuration
public class MvcConfigurer implements WebMvcConfigurer {
    /**
     * 增加拦截器，配置需要跳过token验证的url
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //用户拦截
        registry.addInterceptor(new MyInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/open/**")
                .excludePathPatterns("/v3/api-docs/**");
    }
}

class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = dateFormat.format(new Date());
        // 设置MDC字段
        ThreadContext.put("timestamp", now);
        ThreadContext.put("threadId", "threadId");
        ThreadContext.put("traceId", "traceId");
        ThreadContext.put("logLevel", "logLevel");
        ThreadContext.put("appName", "appName");
        ThreadContext.put("sysName", "系统设置");
        ThreadContext.put("modName", "模型名称");
        ThreadContext.put("branch", "{\"applicationId\":944,\"companyId\":2000}");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        // 清除MDC字段
        ThreadContext.clearMap();
    }


}
